<template>
  <div class="createPost-container">
    <el-divider content-position="left">用户信息</el-divider>
    <el-form
      ref="postForm"
      :model="postForm"
      :rules="rules"
      class="form-container"
      :disabled="isView"
    >
      <div class="createPost-main-container">
        <el-row gutter="80">
          <el-col :span="12">
            <div class="postInfo-container">
              <el-row>
                <el-form-item
                  style="margin-bottom: 40px"
                  prop="userName"
                  label-width="180px"
                  label="中文名："
                >
                  <el-input
                    v-model="postForm.userName"
                    :maxlength="100"
                    name="name"
                    required
                  >
                  </el-input>
                </el-form-item>
              </el-row>
              <el-row>
                <el-form-item
                  style="margin-bottom: 40px"
                  prop="employeeId"
                  label-width="180px"
                  label="员工编号："
                >
                  <el-input
                    v-model="postForm.employeeId"
                    :maxlength="100"
                    name="name"
                  >
                  </el-input>
                </el-form-item>
              </el-row>
              <el-row>
                <el-form-item
                  style="margin-bottom: 40px"
                  prop="userEmail"
                  label-width="180px"
                  label="邮箱："
                >
                  <el-input
                    v-model="postForm.userEmail"
                    :maxlength="100"
                    name="name"
                    required
                  >
                  </el-input>
                </el-form-item>
              </el-row>
              <el-row>
                <el-form-item
                  style="margin-bottom: 40px"
                  prop="userPassword"
                  label-width="180px"
                  label="密码："
                >
                  <el-input
                    placeholder="请输入密码"
                    v-model="postForm.userPassword"
                    show-password
                  ></el-input>
                </el-form-item>
              </el-row>
              <el-row>
                <el-form-item
                  style="margin-bottom: 40px"
                  prop="userCellphone"
                  label-width="180px"
                  label="手机号码："
                >
                  <el-input
                    v-model="postForm.userCellphone"
                    :maxlength="100"
                    name="name"
                  >
                  </el-input>
                </el-form-item>
              </el-row>
              <div class="identity-container">
                <el-row>
                  <el-form-item
                    label-width="180px"
                    prop="userIdentity"
                    label="职称:"
                  >
                    <el-select
                      v-model="postForm.userIdentity"
                      :remote-method="getIdentityList"
                      filterable
                      remote
                      placeholder="请选择职称"
                      :loading="loading"
                      required
                    >
                      <el-option
                        v-for="item in identityListOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.label"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-row>
                <el-row>
                  <el-form-item
                    label-width="180px"
                    label="所属部门:"
                    prop="userDepartment"
                  >
                    <el-select
                      v-model="postForm.userDepartment"
                      :remote-method="getDepartmentList"
                      filterable
                      remote
                      placeholder="请选择部门"
                      :loading="loading"
                    >
                      <el-option
                        v-for="item in departmentListOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.label"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-row>
                <el-row>
                  <el-form-item
                    label-width="180px"
                    label="角色组:"
                    prop="userRoles"
                  >
                    <el-select
                      v-model="postForm.userRoles"
                      placeholder="请选择角色组"
                      :loading="loading"
                    >
                      <el-option
                        v-for="item in roleListOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-row>
              </div>
            </div>
          </el-col>

          <el-col :span="12">
            <el-row>
              <el-form-item
                style="margin-bottom: 40px"
                prop="userProfile"
                label-width="180px"
                label="用户头像："
              >
                <el-upload
                  class="avatar-uploader"
                  action="http://localhost:3001/api/users/upload"
                  :show-file-list="false"
                  :on-preview="handlePreview"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                >
                  <img
                    v-if="postForm.userPhotoPath"
                    :src="postForm.userPhotoPath"
                    class="avatar"
                  />
                  <i v-else class="el-icon-plus avatar-uploader-icon"
                    >点击修改头像</i
                  >
                </el-upload>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item
                style="margin-bottom: 40px"
                prop="userId"
                label-width="180px"
                label="身份证号："
              >
                <el-input
                  v-model="postForm.userId"
                  :maxlength="100"
                  name="name"
                >
                </el-input>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item
                style="margin-bottom: 40px"
                prop="userGender"
                label-width="180px"
                label="性别："
              >
                <template>
                  <el-radio v-model="postForm.userGender" label="男"
                    >男</el-radio
                  >
                  <el-radio v-model="postForm.userGender" label="女"
                    >女</el-radio
                  >
                </template>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item
                style="margin-bottom: 40px"
                prop="userBirthday"
                label-width="180px"
                label="出生日期："
              >
                <el-date-picker
                  v-model="postForm.userBirthday"
                  type="date"
                  placeholder="请选择日期"
                >
                </el-date-picker>
              </el-form-item>
            </el-row>
          </el-col>
        </el-row>
      </div>
    </el-form>
    <el-divider v-if="isShowSpecialistDetail" content-position="left">专家信息</el-divider>
    <el-divider v-if="isShowResearcherDetail" content-position="left">科研人员信息</el-divider>
    <SpecialistDetail :id="postForm.id" v-if="isShowSpecialistDetail" ref="SpecialistDetail"/>
    <ResearcherDetail :id="postForm.id" v-if="isShowResearcherDetail" ref="ResearcherDetail"/>
    <el-button
      v-show="!isView"
      v-loading="loading"
      style="margin-left: 230px; width: 100px"
      type="success"
      @click="submitForm"
    >
      保存
    </el-button>
  </div>
</template>

<script>
import identityList from "@/data/identities";
import departmentList from "@/data/departments";
import { fetchAllRoles } from "@/api/role";
import { fetchUserById, createUser, updateUser } from "@/api/user";
import SpecialistDetail from "./SpecialistDetail.vue";
import ResearcherDetail from "./ResearcherDetail.vue";
const defaultForm = {
  isUpdatePassword: false,
  userId: "", // 身份证号
  userName: "", // 中文名
  employeeId: "", // 员工编号
  userPassword: "", // 登录密码
  userPhotoPath: "", // 头像
  userRoles: '', // 角色组
  userEmail: "", // 邮箱
  userCellphone: "", // 手机号
  userGender: "男", // 性别
  userBirthday: "", // 出生年月日
  userDepartment: "", // 部门
  userIdentity: "", // 职称
  userToken: '', // login token
  id: undefined,
};

export default {
  name: "UserDetail",
  components: {
    SpecialistDetail,
    ResearcherDetail
  },
  props: {
    isEdit: {
      type: Boolean,
      default: false,
    },
    isView: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("此为必填项"));
      } else {
        callback();
      }
    };

    const validateChinese = (rule, value, callback) => {
      if (!value || value === "") {
        callback(new Error("此为必填项"));
      } else if (/^[\u4e00-\u9fa5]+$/.test(value) === false) {
        callback(new Error("请输入中文"));
      } else {
        callback();
      }
    };

    const validateEmployeeId = (rule, value, callback) => {
      if (/^([a-zA-Z0-9]){5}$/.test(value) === false) {
        callback(new Error("请输入5位员工编号"));
      } else {
        callback();
      }
    };

    const validatePhone = (rule, value, callback) => {
      const regExp = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
      if (!regExp.test(value)) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    };

    const validateId = (rule, value, callback) => {
      var city = { 11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古", 21: "辽宁", 22: "吉林", 23: "黑龙江 ", 31: "上海", 32: "江苏", 33: "浙江", 34: "安徽", 35: "福建", 36: "江西", 37: "山东", 41: "河南", 42: "湖北 ", 43: "湖南", 44: "广东", 45: "广西", 46: "海南", 50: "重庆", 51: "四川", 52: "贵州", 53: "云南", 54: "西藏 ", 61: "陕西", 62: "甘肃", 63: "青海", 64: "宁夏", 65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国外 " };
      var tip = ""
      var pass = true
      if (!value || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(value)) {
        tip = "身份证号格式错误"
        pass = false;
      } else if (!city[value.substr(0, 2)]) {
        // tip = "地址编码错误"
        tip="身份证输入错误"
        pass = false
      }
      // else {
      //   // 18位身份证需要验证最后一位校验位
      //   if (value.length === 18) {
      //     value = value.split('')
      //     // ∑(ai×Wi)(mod 11)
      //     // 加权因子
      //     var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
      //     // 校验位
      //     var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2]
      //     var sum = 0
      //     var ai = 0
      //     var wi = 0
      //     for (var i = 0; i < 17; i++) {
      //       ai = value[i]
      //       wi = factor[i]
      //       sum += ai * wi
      //     }
      //     var last = parity[sum % 11];
      //     if (parity[sum % 11] != value[17]) {
      //       // tip = "校验位错误"
      //       tip="身份证输入错误"
      //       pass = false
      //     }
      //   }
      // }
      if (!pass) {
        callback(new Error(tip))
      } else {
        callback()
      }
    }

    return {
      postForm: Object.assign({}, defaultForm),
      loading: false,
      roleList: [],
      roleListOptions: [],
      identityListOptions: identityList,
      departmentListOptions: departmentList,
      rules: {
        userName: [{ required: true, validator: validateRequire }],
        employeeId: [{ required: true, validator: validateEmployeeId }],
        // userEmail: [{
        //     type: "email",
        //     message: "邮箱格式不正确",
        //     trigger: "change",
        //   }],
        userPassword: [
        { message: "密码不能为空", trigger: "blur" },
          {
            min: 6,
            max: 100,
            message: "长度至少为6",
            trigger: "blur",
          },
        ],
        // userId: [{validator: validateId}],
        // userCellphone: [{ validator: validatePhone }],
        // userIdentity: [{ required: true, validator: validateRequire }],
        userDepartment: [{ required: true, validator: validateRequire }],
        userRoles: [{ required: true, validator: validateRequire }],
      },
    };
  },
  created() {
    this.fetchRoleList();
    if (this.isEdit || this.isView) {
      const id = this.$route.params && this.$route.params.id;
      this.fetchData(id);
    }
  },
  computed: {
    // 展示专家表单
    isShowSpecialistDetail() {
      return this.postForm.userRoles == 6;
    },
    // 展示科研人员表单
    isShowResearcherDetail() {
      return this.postForm.userRoles == 7;
    },
  },
  methods: {
    handlePreview(file) {
      let a = document.createElement('a');
      let event = new MouseEvent('click');
      a.download = file.name;
      a.href = file.response? `http://localhost:3001/${file.response.srcurl}` : file.url;
      a.dispatchEvent(event);
      console.log(file);
    },
    fetchRoleList() {
      this.listLoading = true;
      fetchAllRoles().then((res) => {
        this.roleList = res.data.map((item) => {
          return { label: item.roleName, value: item.id };
        });
        this.roleListOptions = this.roleList;

        this.listLoading = false;
      });
    },
    getIdentityList(query) {
      if (query !== "") {
        this.loading = true;
        this.identityListOptions = identityList.filter((item) => {
          return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
        });
        this.loading = false;
      } else {
        this.identityListOptions = identityList;
      }
    },
    getDepartmentList(query) {
      if (query !== "") {
        this.loading = true;
        this.departmentListOptions = departmentList.filter((item) => {
          return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
        });
        this.loading = false;
      } else {
        this.departmentListOptions = departmentList;
      }
    },
    getRoleList(query) {
      if (query !== "") {
        this.loading = true;
        this.roleListOptions = roleList.filter((item) => {
          return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
        });
        this.loading = false;
      } else {
        this.roleListOptions = roleList;
      }
    },
    fetchData(id) {
      fetchUserById(id)
        .then((res) => {
          this.postForm = res.data[0];
          this.postForm.userRoles = this.postForm.userRoles
            ? JSON.parse(this.postForm.userRoles)[0]
            : '';
        })
        .catch((err) => {
          console.log(err);
        });
    },
    handleAvatarSuccess(res, file) {
      if (res.status === "1") return this.$message.error(res.message);
      this.postForm.userPhotoPath = `http://localhost:3001/${res.srcurl}`;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 5;

      if (!isJPG) {
        this.$message.error("Avatar picture must be JPG format!");
      }
      if (!isLt2M) {
        this.$message.error("Avatar picture size can not exceed 5MB!");
      }
      return isJPG && isLt2M;
    },
    submitForm() {
      this.$refs.postForm.validate(  async (valid) => {
        if (valid) {
            if (this.isShowSpecialistDetail) {
                await this.$refs.SpecialistDetail.checkForm();
            } else if (this.isShowResearcherDetail) {
                await this.$refs.ResearcherDetail.checkForm();
            }
          this.loading = true;
          if (this.postForm.id) {
            updateUser(this.postForm.id, {
              ...this.postForm,
              id: undefined,
              userRoles: [this.postForm.userRoles]
            })
              .then(async (res) => {
                if (res.data) {
                    if (this.isShowSpecialistDetail) {
                        await this.$refs.SpecialistDetail.submitForm();
                    } else if (this.isShowResearcherDetail) {
                        await this.$refs.ResearcherDetail.submitForm();
                    }
                  this.$message({
                    title: "成功",
                    message: "用户信息更新成功",
                    type: "success",
                    duration: 2000,
                  });
                } else {
                  this.$message({
                    message: "用户信息更新失败",
                    type: "error",
                  });
                }
                this.loading = false;
              })
              .catch((err) => {
                this.loading = false;
              });
          } else {
            createUser({
                ...this.postForm,
                userRoles: [this.postForm.userRoles]
            })
              .then(async (res) => {
                if (res.data) {
                    if (this.isShowSpecialistDetail) {
                        await this.$refs.SpecialistDetail.submitForm({ id: res.data});
                    } else if (this.isShowResearcherDetail) {
                        await this.$refs.ResearcherDetail.submitForm({ id: res.data});
                    }
                  this.$message({
                    title: "成功",
                    message: "用户创建成功",
                    type: "success",
                    duration: 2000,
                  });
                } else {
                  this.$message({
                    message: "用户创建失败",
                    type: "error",
                  });
                }
                this.loading = false;
              })
              .catch((err) => {
                this.loading = false;
              });
          }
        } else {
          console.log("用户信息保存失败");
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9 !important;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 18px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }
}

.identity-container {
  margin-top: 50px;
}
</style>
